package com.chenjl.transaction.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.chenjl.transaction.dao.TbRabbitmqSendLogMapper;
import com.chenjl.transaction.dto.MessageQueueBody;
import com.chenjl.transaction.model.TbRabbitmqSendLog;

import lombok.extern.slf4j.Slf4j;
/**
 * 消息从交换器发送到对应队列失败时触发, 如指定的routingKey找不到队列
 * 2019-3-18 14:09:55
 * @author chenjinlong
 */
@Slf4j
@Service("rabbitMQReturnCallback")
public class RabbitMQReturnCallback implements ReturnCallback {

	@Autowired
	private TbRabbitmqSendLogMapper tbRabbitmqSendLogMapper;
	
	
	@Override
	public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
		String messageQueueBodyStr = new String(message.getBody());
		
		log.info("ReturnCallback.....--->>---messageQueueBodyStr:{},replyCode:{},replyText:{},exchange:{},routingKey:{}",
				messageQueueBodyStr,
				replyCode,
				replyText,
				exchange,
				routingKey);
		
		this.updateRabbitMqSendLog(messageQueueBodyStr);
	}
	/**
	 * 更新QueueStatus状态
	 * @param messageQueueBodyStr
	 */
	private void updateRabbitMqSendLog(String messageQueueBodyStr) {
		try {
			//从消息体中获取flowId
			MessageQueueBody messageQueueBody = JSONObject.parseObject(messageQueueBodyStr,MessageQueueBody.class);
			String flowNo = messageQueueBody.getFlowNo();
			
			if(StringUtils.isNotBlank(flowNo)) {
				TbRabbitmqSendLog queryTbRabbitmqSendLog = new TbRabbitmqSendLog();
				queryTbRabbitmqSendLog.setFlowNo(flowNo);
				queryTbRabbitmqSendLog.setIsDeleted(false);
				List<TbRabbitmqSendLog> tbRabbitmqSendLogs = tbRabbitmqSendLogMapper.selectPageSelective(queryTbRabbitmqSendLog,new PageRequest(0,1));
				
				if(tbRabbitmqSendLogs.size() > 0) {
					TbRabbitmqSendLog tbRabbitmqSendLog = tbRabbitmqSendLogs.get(0);
				
					TbRabbitmqSendLog updateTbRabbitmqSendLog = new TbRabbitmqSendLog();
					updateTbRabbitmqSendLog.setId(tbRabbitmqSendLog.getId());
					updateTbRabbitmqSendLog.setRouteStatus(false);
					updateTbRabbitmqSendLog.setUpdateTime(new Date());
					tbRabbitmqSendLogMapper.updateByPrimaryKeySelective(updateTbRabbitmqSendLog);
				}
			}
		}
		catch(Exception e) {
			log.error("this should not happened:{}",e);
		}
	}
}